package com.edu.lxshpc.filter;

import cn.hutool.json.JSONUtil;
import com.edu.lxshpc.pojo.User;
import com.edu.lxshpc.utils.MyException;
import com.edu.lxshpc.utils.Result;
import com.edu.lxshpc.utils.Utils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zgh
 * @date 2023/11/2
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static String key = "key-";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Authorization");
        //为空放行
        if ("".equals(token) || token == null) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //判断token是否有效
            if (!token.startsWith("Bearer")) {
                log.error("token格式错误");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json");
                response.getWriter().println(JSONUtil.toJsonStr(Result.fail("token格式错误")));
                response.getWriter().flush();
                return;
            }
        //解析token
        User user = Utils.parseToken(token);
        if (Objects.isNull(user)) {
            log.error("token无效");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().println(JSONUtil.toJsonStr(Result.fail("token无效")));
            response.getWriter().flush();
            return;
        }
        String authority = user.getAuthority();
        String[] strings = authority.split(",");
        List<GrantedAuthority> collect = Arrays.
                stream(strings).
                map(item -> new SimpleGrantedAuthority(item))
                .collect(Collectors.toList());
        user.setAuthorities(collect);

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        // 将请求中的详细信息（即：IP、SessionId 等）封装到 UsernamePasswordAuthenticationToken 对象中方便后续校验
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
